<template>
<div class="slider-bar-wrap" id="area">
  <div class="slider-bar" :class="{'white':whitebar}">
    <div class="-handle" :style="{left: currentX + 'px'}" @tap.stop="$emit('tap-handle')" @touchstart="onDragStart" @touchmove.stop="onDraging" @touchend.stop="onDragStop">
      <i class="fi" :class="{'icon-bofang': !isChanging, 'icon-zanting': isChanging}"></i>
    </div>
    <div class="-process lg" :style="{width: currentX + 'px'}"></div>
  </div>
</div>
</template>

<script>
export default {
  props: {
    isChanging: {
      type: Boolean,
      default: 0
    },
    value: {
      type: Number,
      default: 0
    },
    whitebar: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      totalWidth: 0,
      startPageX: 0,
      currentPageX: 0,
      distantX: 0
    }
  },
  computed: {
    currentX() {
      let t = this.x + this.distantX
      if (t <= 0) return 0
      if (t >= this.totalWidth - 10) return this.totalWidth - 10
      return t
    }
  },
  methods: {
    onHandleTap() {},
    onDragStop() {
      this.x = this.currentX
      let pc = Math.round(this.currentX / (this.totalWidth - 10) * 100)
      this.$emit('change', pc)
      this.$emit('drag-end')
    },
    onDragStart(e) {
      this.startPageX = e.pageX
      this.x = this.currentX
      this.$emit('drag-start')
    },
    onDraging(e) {
      this.currentPageX = e.pageX
    }
  },
  mounted() {
    this.x = 0
    let that = this
    setTimeout(() => {
      wx
        .createSelectorQuery()
        .select('#area')
        .boundingClientRect(function(rect) {
          that.totalWidth = rect.width
        })
        .exec()
    }, 100)
  },
  watch: {
    totalWidth(nv) {
      this.distantX = this.value / 100 * nv
    },
    currentPageX(nv) {
      this.distantX = nv - this.startPageX
    },
    value(nv) {
      this.distantX = nv / 100 * this.totalWidth
      this.x = 0
    }
  }
}
</script>

<style scoped lang="less">
@import '../assets/less/var.less';
.slider-bar-wrap {
  width: 100%;
}
.slider-bar {
  position: relative;
  width: 100%;
  height: 8px;
  background-color: lighten(@colorGray, 20%);
  border-radius: 5px;

  &.white {
    background-color: @colorWhite;
  }
}
.-handle {
  position: absolute;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  top: -15px;
  background-color: @colorWhite;
  transition: left 0.2s;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  z-index: 100;
  text-align: center;
  line-height: 36px;
  i {
    position: relative;
    font-size: 1.2em;
    color: @colorYellow;
    &.icon-bofang {
      left: 2px;
    }
  }
}
.-process {
  transition: width 0.2s;
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
}
</style>
